package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        //获取每日营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //将localdate类型转换为localdatetime

            //获取date当天的0点0分0秒的localdatetime形式的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //若当天营业额为null，则设置为0.0
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        //获取用户总量列表
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //获取date当天的0点0分0秒的localdatetime形式的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            map.put("beginTime", beginTime);
            //每天的新增用户就是当天注册的用户
            Integer newUser = userMapper.countByMap(map);
            newUser = newUser == null ? 0 : newUser;

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        dateList.add(end);
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        Double orderCompletionRate = 0.0;
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取date当天的0点0分0秒的localdatetime形式的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            //查询今天的订单总数
            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            //查询今天的有效订单数量
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);

        }

        //TODO reduce方法
        //reduce(0,Integer::sum) -> 从0开始累加集合中的元素
        Integer totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);
        Integer validOrderCount = validOrderCountList.stream().reduce(0, Integer::sum);
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO salesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.top10(beginTime, endTime);
        // TODO 方法引用代替lambda表达式
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String name = StringUtils.join(nameList, ",");
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String number = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO
                .builder()
                .nameList(name)
                .numberList(number)
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //查询昨天到前30天的数据
        LocalDate end = LocalDate.now().plusDays(-1);
        LocalDate begin = LocalDate.now().plusDays(-30);
        XSSFWorkbook excel = null;
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/turnoverReport.xlsx");
        try {
            //创建excel对象
            excel = new XSSFWorkbook(resourceAsStream);
            //拿到excel表格中的sheet1
            XSSFSheet sheet1 = excel.getSheetAt(0);
            //拿到sheet1的第2行中的第2个单元格
            sheet1.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);

            BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            sheet1.getRow(3).getCell(2).setCellValue(data.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(data.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(data.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(data.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(data.getUnitPrice());


            for (int i = 0; i < 30; i++) {
                BusinessDataVO dayData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(i+7);
                row.getCell(1).setCellValue(begin.toString());
                row.getCell(2).setCellValue(dayData.getTurnover());
                row.getCell(4).setCellValue(dayData.getOrderCompletionRate());
                row.getCell(6).setCellValue(dayData.getNewUsers());
                row.getCell(3).setCellValue(dayData.getValidOrderCount());
                row.getCell(5).setCellValue(dayData.getUnitPrice());
                begin = begin.plusDays(1);
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                excel.close();
                resourceAsStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }



}
